/**
 * 邮箱简历获取记录（明细）
 */
import React from 'react';
import { Table, Form, Input, DatePicker, Button, message } from 'antd';
import { history } from 'umi'
import moment from 'moment';
import { isArray } from 'lodash';
import { PageContainer } from '@/molecules';
import { Pagination } from '@/components';
import { useRequest } from '@/hooks';
import { Link } from '../components';
import { getResumeRecords } from '../Channel/service';
import { getChannelListWithoutTalent } from './service';

function EmailHistoryDetail({ form, location }) {
    const { query = {} } = location;
    const { data, loading, run } = useRequest(getResumeRecords, {
        manual: true
    });
    const dataSource = data?.data?.rows || [];
    const total = data?.data?.total || 0;

    const { data: channelList } = useRequest(() => getChannelListWithoutTalent({ channelStatus: 1 }), {
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data: temp, msg } = res;
                if (code === 10000) {
                    return temp.map(item => ({
                        text: item.channelName,
                        value: item.channelCode
                    }));
                }
                message.error(msg);
            }
            return [];
        }
    });

    React.useEffect(() => {
        const { orderByField = '', channelCode = [], activeKey, ...rest } = query;
        const channelCodes = isArray(channelCode) ? channelCode : [channelCode];
        run({
            ...rest,
            orderByField: orderByField.replace('end', ''),
            channelCodes
        });
    }, [query]);

    const columns = [
        {
            title: '邮箱',
            dataIndex: 'fetchMail'
        },
        {
            title: '来源',
            dataIndex: 'channelName',
            filteredValue:
                query?.channelCode && (isArray(query?.channelCode) ? query?.channelCode : [query?.channelCode]),
            filters: channelList
        },
        {
            title: '岗位',
            dataIndex: 'dutyName'
        },
        {
            title: '简历',
            dataIndex: 'resumeName',
            render: (text, record) => (
                <Link
                    to={{
                        pathname: '/office/personnelManagement/recruitment/resume/detail',
                        query: { id: record.resumeId }
                    }}
                >
                    {text}
                </Link>
            )
        },
        {
            title: '时间',
            dataIndex: 'operateTime',
            sortOrder: query.orderByField ? query.orderByField.split('|')[1] : undefined,
            sorter: () => {},
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : text)
        }
    ];

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.push({ query: { ...query, pageNo: current, pageSize } });
    };

    const handleTableChange = (_, filters = {}, sorter) => {
        const { channelName } = filters;
        const { field, order } = sorter;
        history.push({
            query: {
                ...query,
                channelCode: channelName,
                orderByField: order ? `${field}|${order}` : '',
                pageNo: 1
            }
        });
    };

    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (!err) {
                const { rangeTime, ...rest } = values;
                history.push({
                    query: {
                        ...query,
                        ...rest,
                        operateStartDate: rangeTime?.length > 0 ? rangeTime[0].format('YYYY-MM-DD') : '',
                        operateEndDate: rangeTime?.length > 1 ? rangeTime[1].format('YYYY-MM-DD') : '',
                        pageNo: 1
                    }
                });
            }
        });
    };

    return (
        <PageContainer>
            <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 16 }}>
                <Form.Item label="邮箱">
                    {form.getFieldDecorator('fetchMail', {
                        initialValue: query?.fetchMail || ''
                    })(<Input style={{ width: 148 }} placeholder="请输入邮箱" allowClear />)}
                </Form.Item>
                <Form.Item label="岗位">
                    {form.getFieldDecorator('dutyName', {
                        initialValue: query?.dutyName || ''
                    })(<Input style={{ width: 148 }} placeholder="请输入岗位" allowClear />)}
                </Form.Item>
                <Form.Item label="简历">
                    {form.getFieldDecorator('resumeName', {
                        initialValue: query?.resumeName || ''
                    })(<Input style={{ width: 148 }} placeholder="请输入简历" allowClear />)}
                </Form.Item>
                <Form.Item label="时间">
                    {form.getFieldDecorator('rangeTime', {
                        initialValue:
                            query?.operateStartDate && query?.operateEndDate
                                ? [moment(query.operateStartDate), moment(query.operateEndDate)]
                                : undefined
                    })(<DatePicker.RangePicker style={{ width: 220 }} />)}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
            </Form>
            <Table
                rowKey="id"
                columns={columns}
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onChange={handleTableChange}
                loading={loading}
            />
            <Pagination
                current={query.pageNo}
                pageSize={query.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
        </PageContainer>
    );
}

export default Form.create()(EmailHistoryDetail);
